//
//  AnalysisView.swift
//  Speek
//
//  Created by MikeHo on 2023/6/19.
//

import SwiftUI

import SwiftUI
import CoreData

struct AmountData: Identifiable,Equatable {
    let id = UUID()
    let year: String
    let month: String
    let amount: Double
}

let expenseDataPoints = ["购物", "理财", "旅行", "维修", "学习", "医疗", "饮食", "娱乐", "运动", "其他"]
let incomeDataPoints = ["工资", "奖学金", "礼物", "理财" , "其他"]
let colors: [Color] = [Color(hex: 0x01F1E3), Color(hex: 0x8676FF), Color(hex: 0x3565FC), Color(hex: 0x83CC6F), .yellow, .purple, Color(hex: 0x3285AC), Color(hex: 0x53BC1F), .orange, .brown]

struct AnalysisView: View {
    
    //选择支出或收入
    @State private var selectedTag: Bool = true
    
    //本月总收入和总支出
    @State private var totalIncome: Double = 0
    @State private var totalExpense: Double = 0
    
    //图
    @State private var showBarChart: Bool = true
    @State private var selectedExpense: AmountData? = nil
    @State private var amountDatas: [AmountData] = []
    @State private var dataValues: [Double] = []
    @State private var dataPoints: [String] = []
    
    //选择显示的日期
    @Binding var year : String
    @Binding var month : String
    
    //需要分析的数据
    @Binding var analysisData: AnalysisData
    
    
    init(year: Binding<String>, month: Binding<String>, analysisData: Binding<AnalysisData>) {
        self._year = year
        self._month = month
        self._analysisData = analysisData
        self._amountDatas = State(initialValue: getAmountDatas(year: year.wrappedValue, month: month.wrappedValue, tag: true))
    }

    
    var body: some View {
        VStack {
            
            //选择分析界面显示收入支出类型
            Picker("Transaction Type", selection: $selectedTag) {
                Text("收入").tag(true)
                Text("支出").tag(false)
            }
            .pickerStyle(SegmentedPickerStyle())
            .padding(.horizontal)
            
            ScrollView(.vertical){
                VStack {
                    //点击切换柱状图/饼图按钮
                    HStack{
                        Button(action: {
                            showBarChart.toggle() // 切换按钮状态
                        }) {
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color(hex: 0xC0C9EA).opacity(0.3))
                                .frame(width: 80, height: 40)
                                .overlay(
                                    Text(showBarChart ? "柱状图" : "饼状图")
                                        .foregroundColor(.white)
                                        .font(.system(size: 12))
                                        .bold()
                                )
                                .padding(.top, 10)
                                .padding(.leading, 10)
                        }
                        .padding(.leading,10)
                        Spacer()
                    }
                    Spacer()
                    
                    //显示图表
                    VStack {
                        if dataValues.isEmpty || dataValues.allSatisfy({ $0.isNaN }) {
                            VStack(spacing:20){
                                Text("当前没有可供分析的账单，")
                                Text("快去添加账单吧～")
                            }
                            .font(.system(size:20))
                            .padding(.bottom,120)
                            
                        }
                        else{
                            if showBarChart {
                                BarChartView(dataPoints: $dataPoints, dataValues: $dataValues)
                            } else {
                                PieChartView(dataPoints: $dataPoints, dataValues: $dataValues)
                                    .padding(.leading,50)
                            }
                        }
                    }
                    
                }
                .frame(width: 390, height: 350)
                .background(Color(red:0.04,green: 0.09,blue: 0.16).cornerRadius(20))
                

                //趋势图
                TrendView

                
                
                //最大金额和最大变化
                HStack(spacing: 5) {
                    VStack {
                        MaxAmountView(year: $year, month: $month, tag: $selectedTag, analysisData: $analysisData)
                    }
                    VStack {
                        MaxChangeView(year: $year, month: $month, tag: $selectedTag, analysisData: $analysisData)
                    }
                }
                
            }
        }
        .onAppear{
            if selectedTag{
                dataPoints = incomeDataPoints
            }else{
                dataPoints = expenseDataPoints
            }
            dataValues = getDataValues(tag: selectedTag, year: year, month: month)
            analysisData.totalIncome = getTotalAmount(forYear: Int(year) ?? 0, month: Int(month) ?? 0, tag: true)
            analysisData.totalExpense = getTotalAmount(forYear: Int(year) ?? 0, month: Int(month) ?? 0, tag: false)
            amountDatas = getAmountDatas(year: year, month: month, tag: selectedTag)
        }
        .onChange(of: selectedTag, perform: { _ in
            
            //收入/支出选择变化时，改变dataPoints 和 dataValues的值
            if selectedTag{
                dataPoints = incomeDataPoints
            }else{
                dataPoints = expenseDataPoints
            }
            dataValues = getDataValues(tag: selectedTag, year: year, month: month)
            amountDatas = getAmountDatas(year: year, month: month, tag: selectedTag)
        })
        .onChange(of: year, perform: { _ in
            dataValues = getDataValues(tag: selectedTag, year: year, month: month)
            amountDatas = getAmountDatas(year: year, month: month, tag: selectedTag)
            analysisData.totalIncome = getTotalAmount(forYear: Int(year) ?? 0, month: Int(month) ?? 0, tag: true)
            analysisData.totalExpense = getTotalAmount(forYear: Int(year) ?? 0, month: Int(month) ?? 0, tag: false)
        })
        .onChange(of: month, perform: { _ in
            dataValues = getDataValues(tag: selectedTag, year: year, month: month)
            amountDatas = getAmountDatas(year: year, month: month, tag: selectedTag)
            analysisData.totalIncome = getTotalAmount(forYear: Int(year) ?? 0, month: Int(month) ?? 0, tag: true)
            analysisData.totalExpense = getTotalAmount(forYear: Int(year) ?? 0, month: Int(month) ?? 0, tag: false)
        })
        .onChange(of: totalIncome) { newValue in
            analysisData.totalIncome = newValue
            amountDatas = getAmountDatas(year: year, month: month, tag: selectedTag)
        }
        .onChange(of: totalExpense) { newValue in
            analysisData.totalExpense = newValue
            amountDatas = getAmountDatas(year: year, month: month, tag: selectedTag)
        }
   
        .preferredColorScheme(ColorScheme.dark)
    }
    
    //获取每个数据项
    private func getDataValues(tag: Bool, year: String, month: String) -> [Double] {
        dataValues = []
        guard let yearInt = Int(year) else { return [] } // 使用安全解包
        guard let monthInt = Int(month) else { return [] } // 使用安全解包
        let totalAmount = getTotalAmount(forYear: yearInt, month: monthInt, tag: tag)
    
        for index in 0..<dataPoints.count {
            let dataValue = getTotalAmount(forYear: yearInt, month: monthInt, tag: tag, selectedType: dataPoints[index]) / totalAmount
            dataValues.append(dataValue)
        }
        return dataValues
    }
    
    //判断dataAmount中的amount是否全为0
    private func isDataAmountAllZero(data:[AmountData])->Bool{
        for index in 0...11{
            if data[index].amount != 0{
                return false
            }
        }
        return true
    }
    
    
    //获取折线图每个月的对应金额
    private func getAmountDatas(year: String, month:String, tag: Bool)->[AmountData]{
        var amountDatas: [AmountData] = []
        for index in 0...11{
            let amount = getTotalAmount(forYear: Int(year) ?? 0 , month: index + 1, tag: tag)
            let amountData = AmountData(year: year, month: String(index + 1), amount: amount )
            amountDatas.append(amountData)
        }
        return amountDatas
    }
    

}

extension Color {
    init(hex: UInt, alpha: Double = 1.0) {
        let red = Double((hex >> 16) & 0xFF) / 255.0
        let green = Double((hex >> 8) & 0xFF) / 255.0
        let blue = Double(hex & 0xFF) / 255.0
        self.init(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
    }
}

extension AnalysisView{
  
    var TrendView: some View {
        
        VStack {
            HStack{
                if selectedTag{
                    Text("年度收入趋势")
                        .font(.system(size: 12))
                        .bold()
                        .padding()
                        .background(Color(hex: 0xC0C9EA).opacity(0.3).cornerRadius(10))
                }else{
                    Text("年度支出趋势")
                        .font(.system(size: 12))
                        .bold()
                        .padding()
                        .background(Color(hex: 0xC0C9EA).opacity(0.3).cornerRadius(10))
                }
                Spacer()
            }
            .padding(.top,10)

            LineChartView(year: $year, month: $month, tag: $selectedTag)
                .frame(width: 300, height: 250) // 调整宽度和高度
                .padding(.bottom, 10) // 将折线图向上移动，与文本之间留出空间
            Spacer()
            
        }
        .padding(.leading,20)
        .frame(width: 400,height:400)
        .background(Color(red: 0.04, green: 0.09, blue: 0.16).cornerRadius(20))
    }
}
